const makeConnected = (n, connections) => {
  if (connections.length < n - 1) return -1;
  let groupNum = n;
  let parent = new Array(n);
  const findRoot = (x) => {
    if (x === parent[x]) {
      return x;
    }
    parent[x] = findRoot(parent[x]);
    return parent[x];
  };
  for (let i = 0; i < parent.length; i++) {
    parent[i] = i;
  }

  for (let i = 0; i < connections.length; i++) {
    const aRoot = findRoot(connections[i][0]);
    const bRoot = findRoot(connections[i][1]);
    if (aRoot !== bRoot) {
      groupNum--;
      parent[aRoot] = bRoot;
    }
  }
  return groupNum - 1;
};
